package com.zjzywl.smoke.config;

import com.zjzywl.smoke.authenticate.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private CustomUserDetailsService customUserDetailsService;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.headers().frameOptions().sameOrigin().and().csrf().disable()
		.authorizeRequests()
		.antMatchers("/").hasAnyAuthority("manage", "front")
		.antMatchers("/manage").hasAuthority("manage")
		//.antMatchers("").hasAuthority("fireAlarm")
				// .antMatchers("/alarm/**","/categoryjs/**","/icons/**","/map/**",
				// "/public/**","/webjars/**").permitAll()
				// .anyRequest().authenticated()
		.and().formLogin().loginPage("/login").defaultSuccessUrl("/").permitAll()
				.and().logout()   
				.logoutUrl("/logout");
				 //.and().sessionManagement().maximumSessions(1).expiredUrl("/login");
				// 控制账号只能登陆一次
				// .and().exceptionHandling().accessDeniedPage("/accessDenied");//统一异常处理
				//.and().sessionManagement();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/categoryjs/**", "/icons/**", "/map/**", "/public/**", "/webjars/**", "/upload/**");// "/alarm/**",
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());// new
																								// BCryptPasswordEncoder()

		DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
		daoAuthenticationProvider.setUserDetailsService(customUserDetailsService);
		auth.authenticationProvider(daoAuthenticationProvider);
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

}